package com.codejoys.ssm.web;

import com.codejoys.ssm.domain.User;
import com.codejoys.ssm.dto.BaseResult;
import com.codejoys.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    // 根据名字查询用户，同时查询角色信息
    @GetMapping("users/search01")
    @ResponseBody
    public BaseResult findRolebyUser_Name(String name){

        List<User> roleList = userService.findRolebyUser_Name(name);
        BaseResult baseResult = BaseResult.success();
        baseResult.setData(roleList);
        return baseResult;
    }

    //根据名字模糊查询用户，分页展示
    @GetMapping("users/search02")
    @ResponseBody
    public BaseResult findByUser_Name(User user,
                                 @RequestParam("page") Integer page,
                                 @RequestParam("limit") Integer limit){
        List<User> users = userService.findByUser_Name(user,page,limit);
        BaseResult baseResult = BaseResult.success();
        baseResult.setData(users);
        return baseResult;
    }


    @GetMapping("/")
    public String index(){
        return "index.html";
    }

    @PostMapping("/admin/register")
    public BaseResult register(User user) {
        // 密码要加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setUserName(user.getName());
        user.setCreated(new Date());
        user.setUpdated(new Date());

        userService.register(user);

        return BaseResult.success();
    }



}
